package com.westcom.vulb.logic;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.westcom.vulb.application.GlobalContext;
import com.westcom.vulb.bean.Session;
import com.westcom.vulb.bean.notify_node;
import com.westcom.vulb.db.DbHelper;
import com.westcom.vulb.network.websocket.VulbWebsocket;
import com.westcom.vulb.network.websocket.VulbWebsocket.status;
import com.westcom.vulb.protocal.http.Response;

public class SessionManager {
    private static SessionManager instance = new SessionManager();
    private Session m_current_session;
    private DbHelper db = null;
    private Dao<Session, Integer> mSessionDao;
    private SharedPreferences m_current_logged_user = null;
    public static final String logged_user_info = "user info";
	public static final String current_user_account = "user account";
	public static final String current_user_password = "user password";
	//http
	public static final int HTTP_HEART_BEAT_PERIOD = 60 * 1000;
	public static final int MSG_HTTP_HEART_BEAT = 0x01;
	private static boolean mIsHttpBeating = false;
	private boolean mIsHttpLogin = false;
	//ws
	private static final String Login_id = "sm login id";
	private static final int MSG_WS_LOGIN = 0X02;
	private ws_req mWs = ws_req.getInstance();
	private static final int MSG_WS_STATUS_CHANGED = 0X03;
	private boolean mIsWsBeating = false;
	public static final int WS_HEART_BEAT_PERIOD = 60 * 1000;
	public static final int MSG_WS_HEART_BEAT = 0x04;
	
	private static String TAG = "SessionManager";
	private Handler mHandler = new Handler()
	{
        @Override
        public void handleMessage(Message msg) 
        {
        	switch (msg.what)
        	{
        		case MSG_HTTP_HEART_BEAT:
        		{
        			if(mIsHttpBeating == false)
        			{
        				return;
        			}
        			new HttpHeartBeatTask().execute("");
        		}break;
        		case MSG_WS_LOGIN:
        		{
        			Response res = (Response)msg.obj;
        			
        		}break;
        		case MSG_WS_STATUS_CHANGED:
        		{
        			handlerWsStatusChanged(msg);
        				
        		}break;
        		case MSG_WS_HEART_BEAT:
        		{
        			if(mIsWsBeating == false)
        			{
        				return;
        			}
        			mWs.WsHeartBeat();
        		}break;
        		default: {}break;
        	}
        }
	};
	private void handlerWsStatusChanged(Message msg)
	{
		status s = (status)msg.obj;
		switch(s)
		{
			case disconnected:
			{
				mIsWsBeating = false;
			}break;
			case connecting:
			{}break;
			case connected:
			{
				if(null != m_current_session)
				{
					mWs.Login(m_current_session.getSessionid(),Login_id,mHandler.obtainMessage(MSG_WS_LOGIN));
				}
			}break;
			case logined:
			{
				startWsHeartBeat();
			}break;
			default:{}break;
		}
	}
   
    public SessionManager()
    {
    	mSessionDao = DbHelper.getInstance().getSessionDao(Session.class);
    	m_current_logged_user = GlobalContext.getInstance().getContext().getSharedPreferences(logged_user_info,0);
    	VulbWebsocket.getInstance().registerForStatusChanged(new notify_node(MSG_WS_STATUS_CHANGED,mHandler));
    }
    public static SessionManager getInstance() 
    {
    	if(null == instance)
    	{
    		instance = new SessionManager();
    	}
        return instance;
    }
    public Session getCurrentSession()
    {
    	return mIsHttpBeating?this.m_current_session:null;
    }
    public void login(Session s)
    {
    	this.m_current_session = s;
    	Editor editor = m_current_logged_user.edit();
		editor.putString(current_user_account,s.getAccont());
		editor.putString(current_user_password,s.getpwd());
		editor.commit();
    	try 
    	{
			mSessionDao.createOrUpdate(s);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	StartHttpHeartBeat();
    	mWs.Login(m_current_session.getSessionid(), Login_id, mHandler.obtainMessage(MSG_WS_LOGIN));
    }
    public List<Session> getAllSessions()
    {
    	try 
    	{
			return this.mSessionDao.queryForAll();
		} catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
    }
    public void logout()
    {
    	Editor editor = m_current_logged_user.edit();
		editor.putString(current_user_account,"");
		editor.putString(current_user_password,"");
		editor.commit();
		m_current_session = null;
		mIsHttpBeating = false;
		mIsWsBeating = false;
    }
    public void StartHttpHeartBeat()
    {
    	if(!mIsHttpBeating)
    	{
    		mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_HTTP_HEART_BEAT), HTTP_HEART_BEAT_PERIOD);
        	mIsHttpBeating = true;
    	}
    }
    
    //Test start
    public String getCurrSessionId() {
        //TODO test
//        if (true) {
//            return "283ae0ba-4e24-400f-935d-a20a29f46a0f";
//        }
        
        String sessionId = "";
        
        Session s = m_current_session;
        if (s == null) {
            return "";
        }
        
        sessionId = s.getSessionid();
        if (sessionId == null) {
            sessionId = "";
        }
        return sessionId;
    }
    
    public void setSessionId(String sessionId) {
        if (m_current_session == null) {
            m_current_session = new Session();
        }
        m_current_session.setSessionid(sessionId);
    }
    
    public int getCurrUid() {
        if (m_current_session == null) {
            return -1;
        }
        return m_current_session.getUid();
    }
    //Test end 
    
    //TODO
    private class HttpHeartBeatTask extends AsyncTask<String, Integer, Integer> {
        @Override
        protected Integer doInBackground(String... params) {
        	Response ret = account.getInstanse().HttpHeartBeat(m_current_session.getSessionid());
        	Log.e(TAG,"http heart beat:"+ret.errno);
            return ret.errno;
        }
        @Override  
        protected void onPostExecute(Integer result) 
        {  
        	super.onPostExecute(result);
        	if(result.intValue() == Response.SUCCESS)
			{
				mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_HTTP_HEART_BEAT), HTTP_HEART_BEAT_PERIOD);
			}else
			{
				mIsHttpBeating = false;
			}
        }
    }
    public void startWsHeartBeat()
    {
    	if(!mIsWsBeating)
    	{
    		mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WS_HEART_BEAT), WS_HEART_BEAT_PERIOD);
    		mIsWsBeating = true;
    	}
    }
}